package jok.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopyCharDemo {

	public static void main(String[] args) {
		File file = new File("D:/aa");
		if (!file.exists())
			file.mkdir();

		FileWriterDemo.writeFile3();

		// fileCopy();
		// fileCopy2();
		fileCopy3();

		FileDemo.deleteFile("D:/aa");
		FileDemo.deleteFile("D:/a.txt");
	}

	/**
	 * 使用 字符流 单个字符 形式复制文本文件
	 */
	public static void fileCopy() {
		FileWriter fw = null;
		FileReader fr = null;

		try {
			fw = new FileWriter("D:/aa/a.txt");
			fr = new FileReader("D:/a.txt");

			int num = -1;
			while ((num = fr.read()) != -1) {
				fw.write(num);
			}
			fw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null)
					fr.close();
				if (fw != null)
					fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 使用 字符流 字符数组 形式复制文本文件
	 */
	public static void fileCopy2() {
		FileWriter fw = null;
		FileReader fr = null;

		try {
			fw = new FileWriter("D:/aa/a.txt");
			fr = new FileReader("D:/a.txt");

			char[] cs = new char[1024];
			int num = -1;
			while ((num = fr.read(cs)) != -1) {
				fw.write(cs, 0, num);
				fw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null)
					fr.close();
				if (fw != null)
					fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 使用 高速缓冲字符流 字符数组 形式复制文本文件
	 */
	public static void fileCopy3() {
		BufferedWriter bw = null;
		BufferedReader br = null;

		try {
			bw = new BufferedWriter(new FileWriter("D:/aa/a.txt"));
			br = new BufferedReader(new FileReader("D:/a.txt"));

			char[] cs = new char[1024];
			int num = -1;
			while ((num = br.read(cs)) != -1) {
				bw.write(cs, 0, num);
				bw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
				if (bw != null)
					bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
